package com.blank.web.servlet;

import com.blank.web.bean.UserBean;
import com.blank.web.service.UserService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "loginServlet",urlPatterns = "/login")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、获取请求中的用户名和密码
        String userName = request.getParameter("userName");
        System.out.println("获取到的用户名为:"+userName);
        String password = request.getParameter("password");
        System.out.println("获取到的密码为:"+password);
        //2、创建userService类型的对象实现数据的校验功能
        UserService userService = new UserService();
        UserBean userBean = userService.userLogin(new UserBean(userName, password));
        if(null == userBean){
            System.out.println("登录失败,用户名或密码错误!");
            request.setAttribute("error","登录失败!");
            //实现服务器跳转,共享request和response对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
            requestDispatcher.forward(request,response);
        }else{
            System.out.println("登录成功!");
            request.getSession().setAttribute("user",userBean);
            response.sendRedirect("mainPage.jsp");

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
